import re

import requests
from account.ydt_account_service import YdtAccountService
from model.park_spider import ParkSpider
from model.park_platform import ParkPlatform
from model.car_number import CarNumber
from model.result import Result
from model.error import ParkSpiderError, ParkSpiderErrorCode, TokenExpireError

import dateutil.parser as dateutil

from urllib import parse
import common.http as http
import spider_config
import json
from datetime import datetime
from common.logger import logger
from database.park_location_record_table import ParkLocationRecordTable
import hashlib
import json


class EParkParkSpider(ParkSpider):
    def platform(self) -> ParkPlatform:
        return ParkPlatform(spider_config.epark_park_id)

    def query(self, carNumber: CarNumber) -> Result:
        result = Result()
        result.platform = self.platform()
        result.car_number = carNumber

        account = self.getAccount()

        if not account:
            raise ParkSpiderError(ParkSpiderErrorCode.YdtAccountEmpty)

        privatekey = account["privatekey"]

        data = json.dumps(
            {"carno": str(carNumber), "IsHideName": 1},
            ensure_ascii=False,
            separators=(",", ":"),
        )

        sign = hashlib.md5(
            data.encode("utf-8") + privatekey.encode("utf-8")
        ).hexdigest()

        params = {
            "token": account["token"],
            "ver": "3",
            "client": "3",
            "sign": sign,
            "ua": account["weixinappletopenid"][0:-1],
            "cid": "1",
        }

        url = f"https://mp.ebopark.com/lpn/payment/getProStop"

        headers = {
            "Host": "mp.ebopark.com",
            "Content-Type": "application/json",
            "User-Agent": "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090621) XWEB/8259 Flue",
        }

        rsp = http.post(
            url,
            params=params,
            headers=headers,
            data=data.encode("utf-8"),
            proxies=self.getProxy(),
            timeout=self.getTimeout(),
        )

        if rsp.status_code != 200:
            logger.error(f"e泊车查询失败:{rsp.status_code}")
            return result

        rspJson = rsp.json()

        logger.debug(rspJson)

        if rspJson["state"] == -1001007:
            raise TokenExpireError(account["token"])

        if rspJson["state"] == -1104001:
            result.success = False
            result.message = rspJson["desc"]
            return result

        if rspJson["state"] != 0:
            logger.error(f"e泊车查询未知错误:{rspJson}")
            return result

        # {'state': 0, 'total': 0, 'result': {'parkcode': '510108027', 'parkname': '绑定后展示车场名称>', 'vehicleno': '川LD1H38', 'entertime': '2021-07-22 15:55:44', 'exittime': '2023-07-29 15:57:33', 'alltime': 1061281, 'moneytime': 1061281, 'money': 17689.0, 'totalmoney': 17689.0, 'deductionmoney': 0.0, 'freetime': 15, 'enablecoupon': 1, 'paysupports': [0, 1, 2, 3, 101, 102, 201, 11], 'ActivityDec': {}, 'deductions': [], 'carinimgid': '3331056', 'carintype': 0, 'freeminutes': 0, 'canusetrddedu': False, 'isNeedClear': 0, 'istrdjumppay': False, 'jumppayurl': '', 'Extre': {'IsRcbAggregatePay': 0, 'IsUsedEboPay': 0, 'IsGroupPay': 0, 'IsCarVerify': 0}, 'isDistinctJump': False, 'evasionIds': [], 'evasionMoney': 0.0, 'jointRecoverOrderNum': 0}}

        result.success = True
        result.enter_time = dateutil.parse(rspJson["result"]["entertime"])
        result.platform = self.platform()
        result.price = rspJson["result"]["totalmoney"]

        parkcode = rspJson["result"]["parkcode"]

        with ParkLocationRecordTable() as db:
            result.park_name = db.query_by_code(parkcode)
            if not result.park_name:
                logger.error(f"e泊车车场匹配失败{carNumber}:{parkcode}")

        logger.debug(f"e泊车查询成功:{result}")

        return result
